//
//  StatusViewModel.swift
//  新浪微博
//
//  Created by 焦林生 on 15/11/10.
//  Copyright © 2015年 焦林生. All rights reserved.
//

import UIKit

//微博视图模型  处理单条微博的业务逻辑
class StatusViewModel: CustomStringConvertible {
    
    /**
    *  微博的模型
    */
    var status: Status
    
    //微博创建时间
    var createAt: String? {
    
        return NSDate.sinaDate(status.created_at ?? "")?.dateDescription
    }
    
    //可重用标示符
    var cellID: String {
    
        return status.retweeted_status != nil ? StatusCellRetweetedId : statusCellNormalId
    }

    
    //行高
    lazy var rowHeight: CGFloat = {
       //定义cell
        var cell: StatusCell
        //实例化cell
        if self.status.retweeted_status != nil {
        
             cell = StatusRetweetedCell(style: .Default, reuseIdentifier: StatusCellRetweetedId)
        } else {
        
             cell = StatusNormalCell(style: .Default, reuseIdentifier: statusCellNormalId)
        }
        
        return cell.rowHeight(self)
    }()
    
    //用户头像URL
    var userLProfileUrl: NSURL {
    
        return NSURL(string: status.user?.profile_image_url ?? "")!
    }
    
    //用户默认头像
    var userDefaultIconView: UIImage {
    
        return UIImage(named: "avatar_default_big")!
    }
    //用户会员图标
    var userMemberImage: UIImage? {
    
        //根据mbrank 来生成图像
        if status.user?.mbrank > 0 && status.user?.mbrank < 7 {
        
            return UIImage(named: "common_icon_membership_level\(status.user!.mbrank)")
        }
        return nil
    }
    //用户认证图标
    //认证类型,-1 没有认证0 认证用户  235企业认证 220 达人
    var userVipImage: UIImage? {
    
        switch(status.user?.verified_type ?? -1) {
        case 0: return UIImage(named: "avatar_vip")
        case 2, 3, 5: return UIImage(named: "avatar_enterprise_vip")
        case 220: return UIImage(named: "avatar_grassroot")
        default: return nil
        
        }
        
    }
    //配图url数组
    var thumbnailUrls: [NSURL]?
    
    //被转发原创微博文字
    var retweetedText: String? {
    
        guard let s = status.retweeted_status else {
        
            return nil
        }
        return "@" + (s.user?.screen_name ?? "") + ":" + (s.text ?? "")
    }
    
    
    //构造函数
    //把微博模型传递给视图模型 外界通过视图模型 调用微博数据模型
    init(status: Status) {
        
        self.status = status
        
        //创建配图URL 数组
        let urls = status.retweeted_status?.pic_urls ?? status.pic_urls
        if urls?.count >= 0 {
        
            thumbnailUrls = [NSURL]()
            
            for dict in urls! {
            
                let url = NSURL(string: dict["thumbnail_pic"]!)
                thumbnailUrls?.append(url!)
                
            }
        }
    }
    
    //描述信息
    var description: String {
        
        return status.description + "\n配图数组\((thumbnailUrls ?? []) as NSArray)"
    }
 
    
}
